package org.example.classtopia.Service.Impl;

import org.example.classtopia.Mapper.ResourceLikeMapper;
import org.example.classtopia.Mapper.ResourceMapper;
import org.example.classtopia.Mapper.UserMapper;
import org.example.classtopia.Mapper.UserMassageMapper;
import org.example.classtopia.Model.Entity.UserMessage;
import org.example.classtopia.Service.ResourceLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class ResourceLikeServiceImpl implements ResourceLikeService {
    @Autowired
    private ResourceLikeMapper resourceLikeMapper;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserMassageMapper userMassageMapper;

    @Override
    public boolean likeResource(Long userId, Long resourceId) {
        int rows = resourceLikeMapper.insertResourceLike(userId, resourceId);
        if (rows > 0) {
            UserMessage userMessage = new UserMessage();
            userMessage.setUserId(resourceMapper.selectUserIdByResourceId(resourceId));
            userMessage.setResourceId(resourceId);
            userMessage.setMessageType("resourceLike");
            userMessage.setTime(LocalDateTime.now());
            userMessage.setContent("用户" + userMapper.FindDataByID(Math.toIntExact(userId)).getNickname() +
                    "点赞了你上传的资源");
            userMessage.setIsRead(0);
            userMassageMapper.InsertUserMessage(userMessage);
            resourceMapper.incrementLikeCount(resourceId);
            return true;
        }
        return false;
    }

    @Override
    public boolean unlikeResource(Long userId, Long resourceId) {
        int rows = resourceLikeMapper.deleteResourceLike(userId, resourceId);
        if (rows > 0) {
            userMassageMapper.DeleteResourceLikeUserMessage(userId, resourceId);
            resourceMapper.decrementLikeCount(resourceId);
            return true;
        }
        return false;
    }

    @Override
    public boolean hasLiked(Long userId, Long resourceId) {
        return resourceLikeMapper.hasLiked(userId, resourceId) > 0;
    }

    @Override
    public int countLikes(Long resourceId) {
        return resourceLikeMapper.countResourceLikes(resourceId);
    }
}
